<template>
  <div class="article pad">
    <div class="head">
      <span>{{ tiitleTop }}</span>
    </div>

    <el-tabs @tab-click="tabClick" v-model="activeTabPane">
      <el-tab-pane name="1" label="文章">
        <div class="add-wrap m-t-b">
          <el-form
            :model="article"
            ref="article"
            :rules="rules"
            label-position="top"
          >
            <el-form-item label="设置关键字及标题">
              <div class="label_item" v-for="(item, i) in keywords" :key="i">
                <el-select
                  v-model="item.parentId"
                  clearable
                  placeholder="关键字类别"
                  filterable
                  @change="selectKeyword(item.parentId)"
                >
                  <el-option
                    v-for="k in fatherkeyword"
                    :key="k.keywordId"
                    :value="k.keywordId"
                    :label="k.keywordTitle"
                  ></el-option>
                </el-select>

                <el-select
                  v-model="item.keyword"
                  clearable
                  placeholder="请勿重复添加"
                  filterable
                >
                  <el-option
                    v-for="k in labelList"
                    :key="k.keywordId"
                    :value="k.keywordId"
                    :label="k.keywordTitle"
                  ></el-option>
                </el-select>

                <el-input
                  style="width: 255px"
                  v-model="item.title"
                  placeholder="关键字对应标题"
                />
                <i
                  @click="removeKeyword(i)"
                  class="el-icon-remove-outline label2"
                ></i>
                <i
                  @click="addKeyword()"
                  class="el-icon-circle-plus-outline label1"
                ></i>
              </div>

              <!-- <el-button size="mini" type="primary" @click="addKeyword()">添加关键字</el-button> -->
            </el-form-item>
            <!-- <el-form-item prop="knowledgeName">
              <span>文章标题</span>
              <el-input
                style="width:299px"
                v-model="article.knowledgeName"
                placeholder="文章标题"
                maxlength="20"
                show-word-limit
                clearable

              />
            </el-form-item> -->

            <el-form-item prop="enterpriseId">
              <el-select
                placeholder="所属机构"
                v-model="article.enterpriseId"
                filterable
              >
                <el-option
                  v-for="item in enterpriseList"
                  :key="item.enterpriseId"
                  :label="item.enterpriseName"
                  :value="item.enterpriseId"
                ></el-option>
              </el-select>
            </el-form-item>

            <!-- <el-form-item label="是否收费">
              <el-radio-group v-model="article.knowledgePay">
                <el-radio :label="0">免费</el-radio>
                <el-radio :label="1">收费</el-radio>
              </el-radio-group>
            </el-form-item> -->
            <!-- <el-form-item
              v-if="article.knowledgePay === 1"
              prop="knowledgePrice"
            >
              <el-input
                type="number"
                v-model="article.knowledgePrice"
                placeholder="文章价格(用户查看需要支付的钱数, 单位 元)"
              />
            </el-form-item> -->

            <el-form-item label="是否推荐">
              <el-radio-group v-model="article.isRecommend">
                <el-radio-button :label="0">否</el-radio-button>
                <el-radio-button :label="1">是</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="是否置顶">
              <el-radio-group v-model="article.knowledgeTop">
                <el-radio-button :label="0">否</el-radio-button>
                <el-radio-button :label="1">是</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <!-- <el-form-item label="关联商品">
              <div class="goods-show" v-if="goods.title">
                <img :src="goods.banner" />
                <div>
                  <span>{{ goods.title }}</span>
                  <span>{{ goods.price }}元</span>
                  <a @click="removeGoods">删除</a>
                </div>
              </div>
              <el-button type="primary" @click="openSelectGoods"
                >选择商品</el-button
              >
            </el-form-item> -->

            <el-form-item
              label="文章封面图"
              :error="bannerError"
              prop="knowledgePic"
            >
              <span
                >上传的图片将会展示在文章封面；图片分辨率为：XX*XX；图片大小不得超过2Mb</span
              >
              <el-upload
                class="avatar-uploader"
                action="https://domain.com/placeholder"
                :show-file-list="false"
                :http-request="uploadArticleBanner"
                v-loading="isUploading"
              >
                <img
                  v-if="article.knowledgePic"
                  :src="article.knowledgePic"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <!-- <el-form-item prop="knowledgeDesc">
              <el-input
                rows="15"
                type="textarea"
                maxlength="6000"
                show-word-limit
                placeholder="文章内容"
                v-model="article.knowledgeDesc"
              />
            </el-form-item> -->
            <el-form-item label="文章内容">
              <span>文本最大字数不得超过500字</span>
              <!-- <ckeditor value="Hello, World!" :config="editorConfig"></ckeditor> -->


<editor
                :init="editorOption"
                api-key="limppvsecd2utcimllsoqjuseqw643knnjj8xr82nclfqa1e"
                v-model="editorValue"
              ></editor>


              <!-- <div class="custom-editor_wrap">
                <div class="custom-editor_toolbar">

                  <div class="toolbar-item" @click="editorUploadImg('1')">
                    <img src="../assets/images/toolbar_img.png" />
                  </div>
                  <div class="toolbar-item" @click="editorUploadImg('2')">
                    <img src="../assets/images/toolbar_video.png" />
                  </div>
                </div>
                <div class="editor-text_wrap">
                  <div
                    class="custom-editor"
                    ref="editorContent"
                    contenteditable
                  >
                    {{ article.knowledgeDesc }}
                  </div>
                </div>
              </div> -->
            </el-form-item>
          </el-form>
          <div class="add-footer">
            <el-button type="default" @click="resetArticle">重 置</el-button>

            <el-button
              type="primary"
              :loading="isAdding"
              @click="fetchAddArticle"
              >{{ createArticle }}</el-button
            >
          </div>
        </div>
      </el-tab-pane>

      <!-- ------------------------------------------------------------------ -->

      <el-tab-pane name="2" label="视频">
        <el-form :model="article" :rules="rules" ref="video">
          <el-form-item prop="enterpriseId">
            <div>设置关键字及标题</div>
            <el-form-item label="">
              <div class="label_item" v-for="(item, i) in keywords" :key="i">
                <el-select
                  v-model="item.parentId"
                  clearable
                  placeholder="关键字类别"
                  filterable
                  @change="selectKeyword(item.parentId)"
                >
                  <el-option
                    v-for="k in fatherkeyword"
                    :key="k.keywordTitle"
                    :value="k.keywordId"
                    :label="k.keywordTitle"
                  ></el-option>
                </el-select>

                <el-select
                  v-model="item.keyword"
                  clearable
                  placeholder="关键字"
                  filterable
                >
                  <el-option
                    v-for="k in labelList"
                    :key="k.keywordId"
                    :value="k.keywordId"
                    :label="k.keywordTitle"
                  ></el-option>
                </el-select>
                <el-input
                  style="width: 255px"
                  v-model="item.title"
                  placeholder="关键字对应标题"
                />
                <i
                  @click="removeKeyword(i)"
                  class="el-icon-remove-outline label2"
                ></i>
                <i
                  @click="addKeyword()"
                  class="el-icon-circle-plus-outline label1"
                ></i>
              </div>
              <!-- <el-button size="mini" type="primary" @click="addKeyword()"
              >添加关键字</el-button> -->
              <i @click="addKeyword()" class="el-icon-circle-plus-outline"></i>
              <i @click="removeKeyword()" class="el-icon-remove-outline"></i>
            </el-form-item>

            <el-select
              placeholder="所属机构"
              v-model="article.enterpriseId"
              filterable
            >
              <el-option
                v-for="item in enterpriseList"
                :key="item.enterpriseId"
                :label="item.enterpriseName"
                :value="item.enterpriseId"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="是否收费">
              <el-radio-group v-model="article.knowledgePay">
                <el-radio :label="0">免费</el-radio>
                <el-radio :label="1">收费</el-radio>
              </el-radio-group>
            </el-form-item> -->
          <el-form-item v-if="article.knowledgePay === 1" prop="knowledgePrice">
            <el-input
              type="number"
              v-model="article.knowledgePrice"
              placeholder="文章价格(用户查看需要支付的钱数, 单位 元)"
            />
          </el-form-item>
          <el-form-item label="是否推荐">
            <el-radio-group v-model="article.isRecommend">
              <el-radio-button :label="0">否</el-radio-button>
              <el-radio-button :label="1">是</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="是否置顶">
            <el-radio-group v-model="article.knowledgeTop">
              <el-radio-button :label="0">否</el-radio-button>
              <el-radio-button :label="1">是</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="视频封面图"
            :error="bannerError"
            prop="knowledgePic"
          >
            <el-upload
              class="avatar-uploader"
              action="https://domain.com/placeholder"
              :show-file-list="false"
              :http-request="uploadArticleBanner"
              v-loading="isUploading"
            >
              <img
                v-if="article.knowledgePic"
                :src="article.knowledgePic"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="上传视频">
            <el-upload
              class="avatar-uploader"
              action="https://domain.com/placeholder"
              :show-file-list="false"
              :http-request="uploadVideo"
              v-loading="isUploadingV"
            >
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <video
              v-if="article.knowledgeVideo"
              :src="article.knowledgeVideo"
              controls
              autoplay
            ></video>
          </el-form-item>
          <el-form-item prop="knowledgeDesc">
            <el-input
              rows="5"
              type="textarea"
              maxlength="500"
              show-word-limit
              placeholder="视频简介"
              v-model="article.knowledgeDesc"
            />
          </el-form-item>

          <!-- <el-form-item label="设置关键字及标题">
            <div class="label_item" v-for="(item, i) in keywords" :key="i">
              <el-select v-model="item.keyword" placeholder="关键字" filterable>
                <el-option
                  v-for="k in labelList"
                  :key="k.keywordId"
                  :value="k.keywordId"
                  :label="k.keywordTitle"
                ></el-option>
              </el-select>
              <el-input v-model="item.title" placeholder="关键字对应标题" />
            </div>
            <el-button size="mini" type="primary" @click="addKeyword"
              >添加关键字</el-button
            >
          </el-form-item> -->
        </el-form>
        <el-button type="primary" @click="saveVideo">保存</el-button>
      </el-tab-pane>
    </el-tabs>

    <a class="preview-btn" @click="showPreview = !showPreview">{{
      showPreview ? "关闭" : "预览"
    }}</a>

    <div
      :class="['fitbar-phone', showPreview ? '' : 'hidden']"
      id="fitbarPhone"
      @mousedown="mouseClick"
      @mousemove="mouseMove"
      @mouseup="mouseUp"
      @mouseleave="mouseLeave"
    >
      <div
        class="cursor-active"
        v-if="showCursor"
        :style="{ left: cursorLeft + 'px', top: cursorTop + 'px' }"
      ></div>
      <div class="fitbar-phone-head">
        <div class="phone-head_top">
          <div class="head-camera"></div>
          <span class="phone-time">{{ curTime }}</span>
          <div class="phone-battery">
            <span class="phone-battery_rate">100%</span>
            <div class="phone-battery-model">
              <div></div>
            </div>
          </div>
        </div>
        <div class="phone-navigation">
          <img src="../assets/images/left_icon.png" />
          <div class="phone-navigation_title">文章模拟标题</div>
          <div class="menu-button">
            <div>
              <span></span>
              <span></span>
              <span></span>
            </div>
            <div>
              <span></span>
            </div>
          </div>
        </div>
      </div>
      <div class="phone-body">
        <div class="phone-body-title">文章模拟标题</div>
        <div class="article-info">
          <img
            src="https://fitbar.oss-cn-beijing.aliyuncs.com/a-picture/fitbar.jpg"
            style="width: 24px; height: 24px"
          />
          <span style="color: #242424; font-size: 12px; font-weight: bold"
            >Fitbar健康尺</span
          >
          <b
            style="
              display: block;
              width: 1px;
              height: 16px;
              margin: 0 12px;
              background-color: #b4b4b4;
            "
          ></b>
          <span style="font-size: 12px; color: #b4b4b4">
            999点赞 · 999收藏
          </span>
        </div>
        <div style="padding: 30px 21px 100px 21px" v-html="editorValue"></div>
      </div>
      <div class="footer-btn">
        <div>
          <img src="../assets/images/collect_wait.png" />
          <span>点赞</span>
        </div>
        <div class="share-btn" open-type="share">
          <img
            src="../assets/images/wechat.png"
            style="width: 36rpx; height: 36rpx"
          />
          <span>分享</span>
        </div>
      </div>
    </div>

    <el-dialog title="上传图片" :visible.sync="showUploadImg">
      <el-tabs v-model="activeTabIndex">
        <el-tab-pane label="上传图片" name="1">
          <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :http-request="uploadEditorImgOrVideo"
          >
            <el-button size="small" type="primary">选择图片</el-button>
          </el-upload>
          <div class="preview-box">
            <img
              :src="imgPath"
              style="max-width: 80%; min-width: 40px"
              v-if="imgPath"
            />
          </div>
        </el-tab-pane>
        <!-- <el-tab-pane label="上传视频" name="2" disabled>
          <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            :http-request="uploadEditorVideo"
          >
            <el-button size="small" type="primary">选择视频</el-button>
          </el-upload>
          <div class="preview-box">
            <video v-if="videoPath" :src="videoPath" controls></video>
          </div>
        </el-tab-pane> -->
      </el-tabs>
      <div style="display: flex; justify-content: flex-end">
        <el-button type="primary" @click="confirmUpload" :loading="isDoing"
          >确认上传</el-button
        >
      </div>
    </el-dialog>

    <el-dialog title="裁剪图片" :visible.sync="showCropper">
      <el-button type="primary" @click="confrimCropper">确认裁剪</el-button>
      <div style="height: 500px">
        <vue-cropper
          ref="cropper"
          :img="cropperOption.img"
          :outputSize="cropperOption.size"
          :outputType="cropperOption.outputType"
        ></vue-cropper>
      </div>
    </el-dialog>

    <el-dialog title="选择商品" :visible.sync="showGoods">
      <el-select
        v-model="parentCId"
        @change="fetchChildCategory"
        placeholder="一级类目"
      >
        <el-option
          v-for="item in parentCategoryList"
          :key="item.id"
          :value="item.id"
          :label="item.name"
        ></el-option>
      </el-select>
      <el-select
        v-model="childCId"
        @change="changeChildCategory"
        :loading="childLoading"
        placeholder="二级类目"
      >
        <el-option
          v-for="item in childCategoryList"
          :key="item.id"
          :value="item.id"
          :label="item.name"
        ></el-option>
      </el-select>
      <el-table
        :data="goodsList"
        border
        stripe
        class="m-t-b"
        v-loading="goodsLoading"
      >
        <el-table-column label="商品名称" prop="title"></el-table-column>
        <el-table-column label="商品图片">
          <template slot-scope="scope">
            <img style="width: 200px" :src="scope.row.banner" />
          </template>
        </el-table-column>
        <el-table-column label="原价(元)">
          <template slot-scope="scope"> {{ scope.row.price3 }}元 </template>
        </el-table-column>
        <el-table-column label="销量" prop="salesNum"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="selectGoods(scope.row)"
              >选择</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="flex m-t-b"
        :page-size="10"
        layout="prev, pager, next"
        @current-change="handleGoodsPagi"
        :total="goodsTotal"
      >
      </el-pagination>
    </el-dialog>
  </div>
</template>
<script>
import {
  getAllOrganization,
  getAllKeyWords,
  uploadVideo,
  addKnowledge,
  getArticleInfo,
  getArticleDetile,
  editArticle,
  getkeyWord,
} from "../api/version2";
import EditorBar from '@/components/EditorBar'
import { PRODUCT_URL } from "../util/server";
import { fileToBase64, formatDate, removeSame } from "../util";
import { uploadImage } from "../api";
import { client } from "../util/oss";
import { VueCropper } from "vue-cropper";
import Editor from '@tinymce/tinymce-vue';
// import editor from "../components/Editor";
import {
  getParentCategory,
  getChildCategory,
  getGoodsList,
  getGoodsDetail,
} from "../api/goods";
export default {
  name: "Article",
  data() {
    const validatePrice = (rules, value, callback) => {
      if (!value) {
        return callback(new Error("请设置文章价格"));
      }
      if (Number(value) < 0.1 || Number(value) > 100) {
        return callback(new Error("文章价格在0.1元 ~ 100元之间"));
      }
      callback();
    };
    return {

      // editor: {
      //   info: ''
      // },
      // isClear: false,

      tiitleTop: "添加推文",
      createArticle: "创建文章",
      editorValue: "", // 富文本内容
      showGoods: false,
      parentCategoryList: [], // 商品父级类目
      parentCId: "",
      childCategoryList: [],
      childCId: "",
      goodsList: [],
      goodsTotal: 0,
      goodsLoading: false,
      childLoading: false,
      showCursor: false,
      cursorLeft: 0,
      cursorTop: 0,
      showPreview: true,
      goods: {
        id: "",
        banner: "",
        title: "",
        price: "",
      },
      curTime: "",

      keywordIdList: [],
      knowledgeNameList: [],
      relationIdList: [],
      KnowledgeId: "", //知识ID

      title: "",
      labels: [],
      detail: null,

      showUploadImg: false,
      showCropper: false,
      activeTabIndex: "1",
      imgFile: "",
      videoFile: "",
      imgPath: "",
      videoPath: "",
      activeTabPane: "1",
      cropperOption: {
        img: "",
        size: 1,
        outputType: "png",
      },
      // editorOption: {
      //   height: 500,
      //   menubar: false,
      //   plugins: [
      //     "advlist autolink lists link image charmap print preview anchor",
      //     "searchreplace visualblocks code fullscreen",
      //     "insertdatetime media table paste code help wordcount",
      //   ],
      //   toolbar:
      //     "bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent  | undo redo | link unlink image  | removeformat ",
      // },

      enterpriseList: [],
      labelList: [],
      fatherkeyword: [],
      isUploadingV: false,
      keywords: [
        {
          parentId: "",
          keyword: "",
          title: "",
        },
      ],
      key: [
        {
          keyword: "",
          titlt: "",
        },
      ],
      article: {
        enterpriseId: "", // 企业id
        knowledgeType: 0, // 类型(0文章，1视频，2文章系统，3视频系列)
        knowledgeMainName: "", // 系列名称
        knowledgeVideo: "", // 知识视频
        knowledgePic: "", // 知识图文
        knowledgeDesc: "", // 知识描述
        knowledgePay: 0, // 知识费用(0免费，1收费)
        knowledgePrice: "", // 知识价格
        knowledgeModel: 1, // 上课方式(1线上 2线下)
        isRecommend: 0, //是否推荐
        knowledgeStatus: 0, // 审核状态(0审核中，1已审核，2已拒绝)
        knowledgeTop: 0, // 是否置顶(0普通 1 置顶)
        keywordAndTitle: null,
      },
      bannerError: "",
      isUploading: false,
      isAdding: false,
      isDoing: false,
      editorConfig: {
        filebrowserImageUploadUrl: PRODUCT_URL + "/upload/img",
        toolbar: [["Bold", "Italic", "Underline"]],
      },
      relationshipList: [],
      rules: {
        enterpriseId: [
          { required: true, message: "请选择发布企业", trigger: "change" },
        ],
        knowledgePic: [
          { required: false, message: "请上传封面图", trigger: "change" },
        ],
        knowledgeName: [
          {
            required: true,
            min: 2,
            max: 20,
            message: "文章名称需为2 ~ 20个字符",
            trigger: "change",
          },
        ],
        knowledgeDesc: [
          {
            required: true,
            min: 10,
            max: 6000,
            message: "文章内容为10 ~ 6000个字符",
            trigger: "change",
          },
        ],
        knowledgePrice: [{ required: true, validator: validatePrice }],
      },
      eOption: {
         height: 500,
         menubar: false,
         plugins: [
           'advlist autolink lists link image charmap print preview anchor',
           'searchreplace visualblocks code fullscreen',
           'insertdatetime media table paste code help wordcount'
         ],
         toolbar:
           'undo redo | formatselect | bold italic backcolor | \
           alignleft aligncenter alignright alignjustify | \
           bullist numlist outdent indent | removeformat | help',
        images_upload_handler (blobInfo, success, failure) {
          const base64 = blobInfo.base64();
          const blob = blobInfo.blob();
          let name = `DUDU${Date.now()}${Math.floor(Math.random() * 1000)}`;
          client.put(name, blob)
          .then(res => {
            let path = res.url;
            path = path.replace('http:', 'https:');
            success(path)
          })
          .catch(e => {
            console.error('上传oss error', e);
            failure(e)
          })
        }
       },
      editorOption: {
        height: 500,
        menubar: true,
        branding: false,
//         plugins: [
//           'advlist autolink lists link image charmap print preview anchor',
//           'searchreplace visualblocks code fullscreen',
//           'insertdatetime media table paste code help wordcount'
//         ],
//         toolbar: 'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent  | undo redo | link unlink image  | removeformat ',
plugins: [
           'advlist autolink lists link image charmap print preview anchor',
           'searchreplace visualblocks code fullscreen',
           'insertdatetime media table paste code help wordcount'
         ],
         toolbar:
           'undo redo | formatselect | bold italic backcolor | \
           alignleft aligncenter alignright alignjustify | \
           bullist numlist outdent indent | removeformat | help',
images_upload_handler (blobInfo, success, failure) {
          const base64 = blobInfo.base64();
          const blob = blobInfo.blob();
          let name = `DUDU${Date.now()}${Math.floor(Math.random() * 1000)}`;
          client.put(name, blob)
          .then(res => {
            let path = res.url;
            path = path.replace('http:', 'https:');
            success(path)
          })
          .catch(e => {
            console.error('上传oss error', e);
            failure(e)
          })
        }
      },
    };
  },
  components: {
    VueCropper,
    // VueQuillEditor
    // EditorBar,
    'editor': Editor
  },
  methods: {
    getEditorContent(data) {
      this.wangValue = data;
    },

    resetArticle() {
      // 重置文章
      console.log("reset");
    },
    mouseClick(e) {
      // 鼠标点击
      if (e.button === 0) {
        // 左键
        this.showCursor = true;
      }
    },
    mouseMove(e) {
      // 鼠标移动
      const el = document.getElementById("fitbarPhone");
      const offsetTop = el.offsetTop;
      const offsetLeft = el.offsetLeft;
      const innerWidth = window.innerWidth;
      const innerHeight = window.innerHeight;
      this.cursorLeft = e.clientX - 13;
      this.cursorTop = e.clientY - 13;
    },
    mouseUp(e) {
      // 鼠标抬起
      if (e.button === 0) {
        this.showCursor = false;
      }
    },
    mouseLeave() {
      this.showCursor = false;
    },
    selectGoods(goods) {
      // 添加商品
      this.goods.id = goods.id;
      this.goods.title = goods.title;
      this.goods.banner = goods.banner;
      this.goods.price = goods.price3;
      this.showGoods = false;
      getGoodsDetail(goods.id)
        .then((res) => {
          console.log(res.data);
        })
        .catch((e) => {});
    },
    openSelectGoods() {
      // 打开选择商品
      this.showGoods = true;
      console.log("选择");
    },
    handleGoodsPagi(page) {
      // 商品分页
      this.fetchGoodsList(page);
    },
    addKeyword() {
      // 添加关键字
      this.keywords.push({
        parentId: "",
        keyword: "",
        title: "",
      });
      this.key.push({
        keyword: "",
        title: "",
      });
    },
    removeKeyword(i) {
      // console.log(keyword.length);
      Math.max(i);
      if (i > 0) {
        this.keywords.splice(i, 1);
        this.key.splice(i, 1);
      } else {
        return this.$message.warning("需保留关键字");
      }
    },
    tabClick({ index }) {
      this.article.knowledgeType = Number(index);
    },
    fetchGetParentCategory() {
      // 查询商品一级类目
      getParentCategory()
        .then((res) => {
          let list = res.data.data || [];
          this.parentCategoryList = list;
        })
        .catch((e) => {});
    },
    fetchChildCategory(id) {
      // 查询商品二级类目
      this.childCategoryList = [];
      this.childCId = "";
      this.goodsList = [];
      this.childLoading = true;
      getChildCategory(id)
        .then((res) => {
          let list = res.data.data || [];
          this.childCategoryList = list;
          this.childLoading = false;
        })
        .catch((e) => {
          this.childLoading = false;
        });
    },
    changeChildCategory(id) {
      // 切换二级类目
      this.fetchGoodsList(1);
    },
    fetchGoodsList(index) {
      // 根据分类查询商品
      this.goodsLoading = true;
      getGoodsList({
        tbSpu: {
          cid1: this.parentCId,
          cid2: this.childCId,
        },
        queryRequest: {
          pageSize: 10,
          pageNum: index,
        },
      })
        .then((res) => {
          let list = res.data.data.rows || [];
          this.goodsTotal = res.data.data.total;
          list.forEach((item) => {
            if (item.images) {
              let list = JSON.parse(item.images).temBanner.split(",");
              item.banner = list[0];
            }
          });
          this.goodsList = list;
          this.goodsLoading = false;
        })
        .catch((e) => {
          this.goodsLoading = false;
        });
    },
    removeGoods() {
      // 删除商品
      this.goods.title = "";
      this.goods.id = "";
      this.goods.banner = "";
      this.goods.price = "";
    },
    // 保存修改文章
    editA() {
      // var relationIdList = this.keywords[0].relationIdList.split(" ");
      // var keywordIdList = this.keywords[0].keywordIdList.split(" ");
      // var title = this.keywords[0].title.split(" ");

      let list = this.keywords.map((item, index) => {
        return [this.relationIdList[index], item.keyword, item.title];
      });
      editArticle({
        keywordAndTitle: list,
        knowledgeId: this.KnowledgeId,
        enterpriseId: this.article.enterpriseId,
        knowledgeVideo: this.article.knowledgeVideo,
        knowledgePic: this.article.knowledgePic,
        // knowledgeModel: this.article.knowledgeModel,
        knowledgeTop: this.article.knowledgeTop,
        knowledgeDesc: this.article.knowledgeDesc,
        isRecommend: this.article.isRecommend,
        // editorValue:this.article.knowledgeDesc
      })
        .then((res) => {
          // this.editorValue = res.data.data.knowledgeDesc
          // console.log(this.editorValue);
          // console.log(res.data.data.knowledgeDesc);

          console.log(res);
          this.$router.push("/operation/article/list");
          this.$message.success("文章修改成功");
          this.isAdding = false;
        })
        .catch((err) => {
          this.$message.error("文章修改失败！");
          this.isAdding = false;
        });
      // console.log(this.keywordIdList);
      // console.log(this.knowledgeNameList);
    },
    fetchAddArticle() {
      // 创建文章 || 保存修改文章
      this.isAdding = true;
      // let inner = this.$refs.editorContent.innerHTML;
      let inner = this.editorValue;
      if (!inner) {
        this.isAdding = false;
        return this.$message.error("文章内容不能为空");
      }
      if (this.keywords.filter((item) => item.keyword).length === 0) {
        this.isAdding = false;
        return this.$message.error("请设置至少一个关键字");
      }
      this.article.knowledgeDesc = inner;
      this.$refs.article.validate((valid) => {
        if (valid) {
          if (this.KnowledgeId) {
            // 修改
            this.editA();
          } else {
            this.isAdding = false;
            this.fetchAdd();
          }
        } else {
          return false;
        }
      });
    },
    saveVideo() {
      // 保存视频
      if (!this.article.knowledgePic) {
        this.isAdding = false;
        return this.$message.error("请上传视频封面图");
      }
      if (!this.article.knowledgeVideo) {
        this.isAdding = false;
        return this.$message.error("请上传视频");
      }
      if (this.keywords.filter((item) => item.keyword).length === 0) {
        this.isAdding = false;
        return this.$message.error("请选择至少一个关键字");
      }
      this.$refs.video.validate((valid) => {
        if (valid) {
          this.fetchAdd();
        } else {
          return false;
        }
      });
    },
    fetchAdd() {
      // 添加知识
      let tempList = this.keywords.map((item) => [item.keyword, item.title]);
      this.article.keywordAndTitle = tempList;
      this.isAdding = false;
      const that = this;
      addKnowledge({
        ...this.article,
        goodsId: this.goods.id || null,
      })
        .then((res) => {
          this.isAdding = false;
          this.$message({
            type: "success",
            message: "创建成功",
            onClose() {
              let url =
                that.activeTabPane == "1"
                  ? "/operation/article/list"
                  : "/operation/video/list";
              that.$router.push(url);
            },
          });
        })
        .catch((e) => {
          this.isAdding = false;
        });
    },
    editorUploadImg(index) {
      // 编辑器上传文章
      if (index == "2") {
        return this.$message.error("暂不支持上传视频");
        this.isAdding = false;
      }
      this.activeTabIndex = index;
      this.showUploadImg = true;
    },
    uploadVideo({ file }) {
      // 上传视频
      this.isUploadingV = true;
      const _this = this;
      fileToBase64(file, (str) => {
        uploadImage(str)
          .then((res) => {
            let path = res.data.data.path;
            path = path.replace("http:", "https:");
            _this.article.knowledgeVideo = path;
            this.isUploadingV = false;
          })
          .catch((e) => {
            this.isUploadingV = false;
          });
      });
    },
    uploadArticleBanner({ file }) {
      // 上传文章封面图
      if (file.type.indexOf("image") === -1) {
        this.isAdding = false;
        return (this.bannerError = "文件格式错误, 请上传图片");
      }
      this.bannerError = "";
      this.isUploading = true;
      const _this = this;
      fileToBase64(file, (str) => {
        // _this.cropperOption.img = str;
        // _this.showCropper = true;
        // setTimeout(() => {
        //   _this.$refs.cropper.startCrop();
        // }, 500);

        uploadImage(str)
          .then((res) => {
            let path = res.data.data.path;
            path = path.replace("http:", "https:");
            console.log(path);
            _this.article.knowledgePic = path;
            _this.isUploading = false;
          })
          .catch((e) => {
            _this.isUploading = false;
          });
      });
    },
    confrimCropper() {
      // 确认裁剪
      this.$refs.cropper.stopCrop();
      this.$refs.cropper.getCropData((data) => {
        console.log("裁剪成功的数据", data);
      });
    },
    fetchAllOrganization() {
      // 查询所有企业
      getAllOrganization()
        .then((res) => {
          let list = res.data.data || [];
          list = list.filter((item) => item.type == "2");
          this.enterpriseList = list;
        })
        .catch((e) => {});
    },
    fetchAllLabels() {
      // 查询所有关键字
      getAllKeyWords()
        .then((res) => {
          let list = res.data.data || [];
          this.labelList = list;
        })
        .catch((e) => {});
    },
    confirmUpload() {
      // 确认上传
      let file = this.activeTabIndex === "1" ? this.imgFile : this.videoFile;
      if (!file) {
        return this.$message.error("请选择文件");
      }
      const that = this;
      this.isDoing = true;
      fileToBase64(file, (fileStr) => {
        uploadImage(fileStr)
          .then((res) => {
            let path = res.data.data.path;
            path = path.replace("http:", "https:");
            that[that.activeTabIndex === "1" ? "imgPath" : "videoPath"] = path;
            this.addInnerHtml();
            this.showUploadImg = false;
            this.isDoing = false;
          })
          .catch((e) => {
            this.isDoing = false;
          });
      });
    },
    addInnerHtml() {
      // 添加图片/视频节点
      let html = "";
      if (this.activeTabIndex === "1") {
        // 文章
        html = `<img src="${this.imgPath}" style="display: block; width: 100%;"></img>`;
      } else if (this.activeTabIndex === "2") {
        // 视频
        html = `<video src="${this.videoPath}" controls style="display: block; width: 100%;"></video>`;
      }
      // let elHtml = this.$refs.editorContent.innerHTML;
      // this.$refs.editorContent.innerHTML = elHtml + html;
      let elHtml = this.editorValue;
      this.editorValue = elHtml + html;
    },
    uploadEditorImgOrVideo({ file }) {
      // 上传图片
      this.imgFile = file;
    },
    uploadEditorVideo({ file }) {
      // 上传视频
      this.videoFile = file;
    },

    fun1() {
      const query = this.$route.query;
      console.log(query);
      getArticleInfo(query.id).then((res) => {
        console.log(res);
        this.article.knowledgePic = res.data.data.knowledgePic;
      });
    },

    alterArticle() {
      const query = this.$route.query;
      // console.log(query);
      if (query.id) {
        this.tiitleTop = "修改文章";
        this.createArticle = "保存修改";
        this.KnowledgeId = query.id;
        getArticleDetile(query.id).then((res) => {
          console.log(res);
          this.editorValue = res.data.data.knowledgeDesc
          let obj = res.data.data || {};
          this.relationIdList = obj.relationIdList;
          // console.log(this.relationIdList);
          // 关键字和标题
          this.keywords = obj.keywordTitleList.map((item, index) => {
            // console.log(obj.keywordIdList[index])
            return {
              keyword: item,
              // <<<<<<< HEAD
              parentId: obj.parentKeywordId[index],
              keyword: obj.keywordTitleList[index],
              // =======
              parentId: obj.parentTitleList[index],
              keyword: obj.keywordTitleList[index],
              keyword: obj.keywordIdList[index],

              // >>>>>>>
              title: obj.knowledgeNameList[index],
            };
          });

          // for (var i = 0; i < res.data.data.keywordIdList.length; i++) {
          //   this.keywordIdList.push(res.data.data.keywordIdList[i]);
          //   this.knowledgeNameList.push(res.data.data.knowledgeNameList[i]);
          //   this.relationIdList.push(res.data.data.relationIdList[i]);
          // }

          // 置顶
          this.article.knowledgeTop = res.data.data.knowledgeTop;

          // 上课方式
          // this.article.knowledgeModel = res.data.data.knowledgeModel;
         
         this.article.isRecommend = res.data.data.isRecommend;

          // 企业id
          this.article.enterpriseId = res.data.data.enterpriseId;

          // 封面图
          this.article.knowledgePic = res.data.data.knowledgePic;

          // 视频简介
          this.article.knowledgeDesc = res.data.data.knowledgeDesc;

          // 知识视频
          this.article.knowledgeVideo = res.data.data.knowledgeVideo;
        });
      }
    },

    getFatherKeyword() {
      // 获取父关键字
      getkeyWord({
        parentId: "0",
      }).then((res) => {
        // console.log(res);
        let list = res.data.data || [];
        this.fatherkeyword = list;
        //   this.key = list.map(item => {
        //   return {
        //     keyword: item.keywordId,
        //     title: item.keywordTitle,
        //   }
        // });
        // console.log(this.key);
      });
    },
    selectKeyword(tab) {
      if (!tab) {
        return;
      } else {
        getkeyWord({
          parentId: tab,
        }).then((res) => {
          this.labelList = res.data.data;
        });
      }
    },
    computeTime() {
      // 计算时间
      setInterval(() => {
        const date = new Date();
        const hour = date.getHours();
        const minute = date.getMinutes();
        this.curTime = `${hour < 10 ? "0" + hour : hour}:${
          minute < 10 ? "0" + minute : minute
        }`;
      }, 1000);
    },
  },

  created() {
    this.activeTabPane = this.$route.query.type || "1";
    this.fetchAllOrganization();
    // this.fetchAllLabels();
    this.alterArticle();
    // 获取父关键字
    this.getFatherKeyword();
    this.fetchGetParentCategory();
    this.computeTime();
  },
};
</script>
<style lang="scss" scoped>
.el-icon-plus:before {
  font-size: 39px;
  color: #1dbc7c;
}

::-webkit-scrollbar {
  width: 10px;
}
/* 滚动槽 */
::-webkit-scrollbar-track {
  -webkit-box-shadow: inset006pxrgba(0, 0, 0, 0.3);
  border-radius: 10px;
}
/* 滚动条滑块 */
::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.1);
  height: 20px;
}
::-webkit-scrollbar-thumb:window-inactive {
  // background:rgba(255,0,0,0.4);
}
.fitbar-phone {
  position: fixed;
  bottom: 20px;
  right: 50px;
  width: 375px;
  height: 812px;
  border-radius: 35px;
  border: 2px solid #000;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
  z-index: 9999;
  background-color: #fff;
  overflow: hidden;
  transition: 0.2s;
  // transform-origin: 187.5px 400px;
  transform-origin: right bottom;
  user-select: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  &.hidden {
    transform: scale(0);
  }
  .cursor-active {
    position: fixed;
    width: 26px;
    height: 26px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    z-index: 99;
  }
  .footer-btn {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 10px 42px 42px 42px;
    box-shadow: 0px -6px 20px rgba(0, 0, 0, 0.04);
    display: flex;
    justify-content: space-between;
    background-color: #fff;
    z-index: 99;
    div {
      display: flex;
      align-items: center;
      img {
        margin-right: 4px;
        width: 20px;
        height: 20px;
      }
      span {
        font-size: 12px;
        color: #707070;
      }
    }
    .share-btn {
      display: flex;
      padding: 0 !important;
      margin: 0 !important;
      align-items: center;
      justify-content: center;
      width: 79px;
      height: 30px;
      background: linear-gradient(266deg, #6edeb1 0%, #1dbc7c 100%) !important;
      border-radius: 15px;
      img {
        margin-right: 4px;
        width: 15px;
        height: 15px;
      }
      span {
        font-size: 12px;
        color: #fff;
      }
    }
  }
  .fitbar-phone-head {
    position: relative;
    height: 84px;
    .phone-head_top {
      position: relative;
      height: 44px;
      display: flex;
      padding: 0 14px 0 10px;
      justify-content: space-between;
      align-items: center;
      .phone-time {
        font-size: 12px;
        color: #242424;
      }
      .phone-battery {
        display: flex;
        align-items: center;
        span {
          padding-right: 5px;
          font-size: 12px;
          color: #242424;
        }
        .phone-battery-model {
          position: relative;
          width: 25px;
          height: 12px;
          border-radius: 3px;
          border: 1px solid #000;
          box-sizing: border-box;
          &::after {
            content: "";
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            right: -4px;
            width: 2px;
            height: 5px;
            background-color: #000;
          }
          div {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 21px;
            height: 8px;
            border-radius: 2px;
            background-color: #000;
            box-sizing: border-box;
          }
        }
      }
      .head-camera {
        position: absolute;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
        height: 30px;
        width: 200px;
        background-color: #000;
        border-radius: 0 0 15px 15px;
      }
    }
    .phone-navigation {
      position: absolute;
      display: flex;
      align-items: center;
      padding: 0 10px 0 8px;
      left: 0;
      right: 0;
      top: 48px;
      height: 32px;
      // background-color: #f8f8f8;
      img {
        flex-shrink: 0;
        width: 22px;
        height: 22px;
      }
      .phone-navigation_title {
        padding: 0 10px;
        flex: 1;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        color: #000;
      }
      .menu-button {
        display: flex;
        flex-shrink: 0;
        align-items: center;
        justify-content: space-between;
        width: 87px;
        height: 32px;
        border-radius: 16px;
        border: 1px solid #999;
        box-sizing: border-box;
        padding: 0 10px;
        span {
          display: block;
          border-radius: 50%;
          background-color: #242424;
        }
        div:nth-of-type(1) {
          display: flex;
          align-items: center;
          span:nth-of-type(2) {
            margin: 0 2px;
            width: 8px;
            height: 8px;
          }
          span:not(:nth-of-type(2)) {
            width: 5px;
            height: 5px;
          }
        }
        div:nth-of-type(2) {
          position: relative;
          width: 18px;
          height: 18px;
          box-sizing: border-box;
          border: 2px solid #242424;
          border-radius: 50%;
          span {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            width: 7px;
            height: 7px;
          }
        }
      }
    }
  }
  .phone-body {
    position: relative;
    height: calc(100% - 84px);
    overflow-y: auto;
    overflow-x: hidden;
    .phone-body-title {
      font-size: 24px;
      font-weight: bold;
      line-height: 33px;
      color: #242424;
      margin: 18px 21px 25px 21px;
    }
    .article-info {
      padding-left: 21px;
      display: flex;
      align-items: center;
    }
  }
}

.preview-btn {
  position: fixed;
  bottom: 100px;
  right: 5px;
  width: 40px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  border-radius: 50%;
  background-color: #4ac493;
  box-shadow: 0px 6px 20px rgba(74, 196, 147, 0.16);
  font-size: 14px;
  color: #fff;
  cursor: pointer;
  z-index: 999;
  // font-weight: bold;
}
.goods-show {
  position: relative;
  margin-bottom: 8px;
  width: 200px;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 0 20px #ccc;
  cursor: pointer;
  &:hover {
    a {
      display: block;
    }
  }
  & > img {
    display: block;
    width: 200px;
  }
  div {
    position: absolute;
    padding: 4px;
    left: 0;
    top: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.5);
    a {
      display: none;
      position: absolute;
      padding: 4px;
      right: 0;
      bottom: 0;
      color: red;
      line-height: 18px;
      font-weight: bold;
    }
    span {
      display: block;
      font-weight: bold;
      line-height: 26px;
      &:nth-of-type(1) {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
        font-size: 20px;
        color: #fff;
      }
      &:nth-of-type(2) {
        color: red;
        font-size: 18px;
      }
    }
  }
}
.article {
  .preview-box {
    text-align: center;
    height: 400px;
    line-height: 400px;
  }
  .custom-editor_wrap {
    border: 2px solid #ccc;
    .custom-editor_toolbar {
      display: flex;
      padding: 5px 0;
      border-bottom: 1px solid #eee;
      background-color: #f8f8f8;
      .toolbar-item {
        margin-right: 10px;
        width: 30px;
        height: 30px;
        text-align: center;
        line-height: 30px;
        cursor: pointer;
        img {
          width: 20px;
          height: 20px;
        }
      }
    }
    .editor-text_wrap {
      height: 500px;
      padding: 10px;
      box-sizing: border-box;
      overflow-y: auto;
    }
    .custom-editor {
      min-height: 100%;
      line-height: 18px;
      background-color: #fff;
      outline: none;
      img {
        min-width: 40px;
        max-width: 200px;
      }
    }
  }
  .add-footer {
    text-align: right;
  }
  .tp {
    display: flex;
    // flex-direction: column-reverse;
  }
  .add-wrap {
    padding-bottom: 20px;
    border-bottom: 1px solid #ccc;
  }
}
.label_item {
  margin-top: 10px;
  display: flex;
}

.label1 {
  font-size: 28px;
  color: #1dbc7c;
}
.label2 {
  font-size: 28px;
  color: red;
}
</style>


